<?php

namespace App\Http\Controllers\Dynamic;

use App\LogicService\Contracts\BloodGlucoseContrastLogicContract;
use App\Models\Dynamic\BloodTest;
use App\Models\Dynamic\BloodThreshold;
use App\Models\Dynamic\Medicalrecord;
use App\Models\Dynamic\SamGlucose;
use App\Models\Dynamic\SamWear;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;

class BloodTestController extends ApiController
{
    /**
     * @var \App\Models\Dynamic\BloodTest
     */

    protected $user;

    protected $bloodTest;

    protected $request;

    protected $medicalrecord;

    protected $bloodThreshold;

    protected $samWear;

    protected $samGlucose;

    protected $bloodGlucoseContrast;

    /**
     * BloodTestController constructor.
     * @param BloodTest $bloodTest
     * @param Medicalrecord $medicalrecord
     * @param BloodThreshold $bloodThreshold
     * @param Request $request
     * @param User $user
     * @param SamWear $samWear
     * @param SamGlucose $samGlucose
     * @param BloodGlucoseContrastLogicContract $bloodGlucoseContrast
     */
    public function __construct(BloodTest $bloodTest, Medicalrecord $medicalrecord,
                                BloodThreshold $bloodThreshold, Request $request,
                                User $user, SamWear $samWear, SamGlucose $samGlucose, BloodGlucoseContrastLogicContract $bloodGlucoseContrast)
    {
        parent::__construct();
        $this->user = $user;
        $this->bloodThreshold = $bloodThreshold;
        $this->medicalrecord = $medicalrecord;
        $this->bloodTest = $bloodTest;
        $this->samWear = $samWear;
        $this->samGlucose = $samGlucose;
        $this->bloodGlucoseContrast = $bloodGlucoseContrast;
        $this->request = $request;
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMonthBloodById()
    {
        $this->validate($this->request, [
            't' => 'string',
            'user_id' => 'required|integer',
        ]);

        $user_id = $this->request->input('user_id');
        $user = $this->user
            ->withoutGlobalScopes()
            ->select('id', 'account')
            ->find($user_id);

        $account = $user->account;
        $time = $this->request->input('t', date('Y-m', time()));

        //开始,结束
        $start_time = Carbon::parse($time)->startOfMonth();
        $end_time = Carbon::parse($time)->endOfMonth();


        $days = $end_time->diffInDays($start_time) + 1;
        $data['data_count'] = $days;
        $data['minDate'] = Carbon::parse($time)->startOfMonth()->toDateTimeString();
        $data['maxDate'] = Carbon::parse($time)->endOfMonth()->toDateTimeString();


        $blood_list = $this->bloodTest
            ->where('ACCOUNT', '=', $account)
            ->whereBetween('CREATETIME', [$start_time->timestamp, $end_time->timestamp])
            ->get()
            ->toArray();


        //整理数据
        $blood_array = [];
        foreach ($blood_list as $k => $v) {
            $create_time = (int)date("d", $v['CREATETIME']);
            $j = $v['TYPE'];
            $blood_array[$create_time][$j] = $v['COUNTS'];
            unset($create_time);
        }


        $blood = [];
        //生成每月天数对应数组
        for ($times = $data['data_count']; $times > 0; $times--) {
            for ($i = 0; $i < 8; $i++) {
                $blood[$times][$i] = isset($blood_array[$times][$i]) ? $blood_array[$times][$i] : null;
            }
        }

        $data['boold_table'] = $blood;

        $userBaseId = $user->id;
        //医院id
        $hospital_id = $user->hospital_id;

        if (!$hospital_id) {
            $hospital_id = 0;
        }

        //获取病例信息

        $medicalrecord = $this->medicalrecord
            ->whereUserbaseid($userBaseId)
            ->select('status', 'id')
            ->orderBy('id', 'desc')
            ->first();

        $usertype = 2;
        if (empty($medicalrecord)) {
            $usertype = 1;
        } else {
            if ($medicalrecord->status != '1') {
                $usertype = 1;
            }
        }

        $blood_thresold1 = $this->bloodThreshold->getOneByType($userBaseId, $usertype, $hospital_id, 1, 1);//针对患者--空腹
        $blood_thresold2 = $this->bloodThreshold->getOneByType($userBaseId, $usertype, $hospital_id, 2, 1);//针对患者--饭后


        //针对患者--空腹
        $data['EmptyNormal'] = [$blood_thresold1->greenlow, $blood_thresold1->greenhigh];
        $data['EmptyNormalHigh'] = [$blood_thresold1->yellowlow, $blood_thresold1->yellowhigh];
        $data['EmptyAbnormalHigh'] = [$blood_thresold1->redlow, $blood_thresold1->redhigh];
        //针对患者--饭后
        $data['EatNormal'] = [$blood_thresold2->greenlow, $blood_thresold2->greenhigh];
        $data['EatNormalHigh'] = [$blood_thresold2->yellowlow, $blood_thresold2->yellowhigh];
        $data['EatAbnormalHigh'] = [$blood_thresold2->redlow, $blood_thresold2->redhigh];


        return $this->response($data);


    }


    /**
     * GlucoseController edit.
     * @return \Illuminate\Http\JsonResponse
     */

    public function edit()
    {

        $this->validate($this->request, [
            't' => 'string',
            'TYPE' => 'integer|required|min:0|max:7',
            'user_id' => 'required|integer',
        ]);


        $user_id = $this->request->input('user_id');
        $user = $this->user
            ->withoutGlobalScopes()
            ->select('id', 'account')
            ->find($user_id);

        $type = $this->request->input('TYPE');
        $counts = $this->request->input('COUNTS');
        $createtime = $this->request->input('t');


        $bloodTest = $this->bloodTest
            ->where('ACCOUNT', '=', $user->account)
            ->where('TYPE', '=', $type)
            ->where('CREATETIME', '=', strtotime($createtime))
            ->first();

        if (!$bloodTest) {
            $bloodTest = new BloodTest;
            $bloodTest->ACCOUNT = $user->account;
            $bloodTest->TYPE = $type;
            $bloodTest->COUNTS = $counts;
            $bloodTest->CREATETIME = strtotime($createtime);
            $result = $bloodTest->save();

        } else {
            if (empty($counts)) {
                $this->bloodTest
                    ->where('ACCOUNT', '=', $user->account)
                    ->where('TYPE', '=', $type)
                    ->whereBetween('CREATETIME', [strtotime($createtime . '00:00:00'), strtotime($createtime . '23:59:59')])
                    ->delete();
            }
            $result = $this->bloodTest
                ->where('ACCOUNT', '=', $user->account)
                ->where('TYPE', '=', $type)
                ->where('CREATETIME', '=', strtotime($createtime))
                ->update(['COUNTS' => $counts]);

        }


        return $this->response(['result' => $result]);
    }


    public function getStatisticsList()
    {

        $this->validate($this->request, [
            'user_id' => 'required|integer',
        ]);
        $user_id = $this->request->input('user_id');
        $user = $this->user
            ->withoutGlobalScopes()
            ->select('id', 'account')
            ->find($user_id);
        $account = $user->account;


        $bloodglucoseContrast_list = $this->bloodGlucoseContrast->getList($account);


        $end_time =  time();
        //开始,结束
        $week_start_time = time() - 7 * 24 * 3600;
        $month_start_time =  time() - 30 * 24 * 3600;
        $three_month_start_time =  time() - 90 * 24 * 3600;


        $week_count = $this->bloodTest
            ->where('ACCOUNT', '=', $account)
            ->whereBetween('CREATETIME', [$week_start_time, $end_time])
            ->count();
        $week_avg = $this->bloodTest
            ->where('ACCOUNT', '=', $account)
            ->whereBetween('CREATETIME', [$week_start_time, $end_time])
            ->avg('COUNTS');

        $month_count = $this->bloodTest
            ->where('ACCOUNT', '=', $account)
            ->whereBetween('CREATETIME', [$month_start_time, $end_time])
            ->count();
        $month_avg = $this->bloodTest
            ->where('ACCOUNT', '=', $account)
            ->whereBetween('CREATETIME', [$month_start_time, $end_time])
            ->avg('COUNTS');
        $three_month_count = $this->bloodTest
            ->where('ACCOUNT', '=', $account)
            ->whereBetween('CREATETIME', [$three_month_start_time, $end_time])
            ->count();
        $three_avg = $this->bloodTest
            ->where('ACCOUNT', '=', $account)
            ->whereBetween('CREATETIME', [$three_month_start_time, $end_time])
            ->avg('COUNTS');

        $result = array(
            'week_array' => array(
                'week_count' => $week_count,
                'week_avg' => $week_avg,
                'high' => 0,
                'low' =>0,
                'normal'=>0
            ),
            'month_array' => array(
                'month_count' => $month_count,
                'month_avg' => $month_avg,
                'high' => 0,
                'low' =>0,
                'normal'=>0
            ),
            'three_month_array' => array(
                'three_month_count' => $three_month_count,
                'three_avg' => $three_avg,
                'high' => 0,
                'low' =>0,
                'normal'=>0
            )
        );
        if($bloodglucoseContrast_list){

            foreach ($bloodglucoseContrast_list as $key => $value) {

                $week_array = $this->bloodTest->getThreeValue($week_start_time, $end_time, $value['type'], $account,$value['max_value'],$value['min_value']);
                $result['week_array']['high'] = $result['week_array']['high'] + $week_array['high'];
                $result['week_array']['low'] = $result['week_array']['low'] + $week_array['low'];
                $result['week_array']['normal'] = $result['week_array']['normal'] + $week_array['normal'];
                $month_array = $this->bloodTest->getThreeValue($month_start_time, $end_time, $value['type'], $account,$value['max_value'],$value['min_value']);
                $result['month_array']['high'] = $result['month_array']['high'] + $month_array['high'];
                $result['month_array']['low'] = $result['month_array']['low'] + $month_array['low'];
                $result['month_array']['normal'] = $result['month_array']['normal'] + $month_array['normal'];
                $three_month_array = $this->bloodTest->getThreeValue($three_month_start_time, $end_time, $value['type'], $account,$value['max_value'],$value['min_value']);
                $result['three_month_array']['high'] = $result['three_month_array']['high'] + $three_month_array['high'];
                $result['three_month_array']['low'] = $result['three_month_array']['low'] + $three_month_array['low'];
                $result['three_month_array']['normal'] = $result['three_month_array']['normal'] + $three_month_array['normal'];

            }

        }


        return $this->response($result);
    }
}
